package com.konsung.presenter.impl;

import com.konsung.bean.PatientBean;
import com.konsung.greendaoUtil.GreenDaoManager;
import com.konsung.greendaoUtil.PatientBeanDao;
import com.konsung.kslibrary.base.BasePresenter;
import com.konsung.presenter.AddPatientPresenter;
import com.konsung.ui.AddPatientActivity;

import org.greenrobot.greendao.query.WhereCondition;

import java.util.ArrayList;
import java.util.List;

/**
 * 逻辑实现类
 */

public class AddPatientPresenterImpl extends BasePresenter<AddPatientActivity> implements
        AddPatientPresenter.Presenter {

    @Override
    public void addPatient(PatientBean bean) {
        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(mvpView);
        //由于前面逻辑已经规定身份证必须18位，在这里采用like函数规避大小写的Xx
        List<PatientBean> patientBeanList = patientDao.queryBuilder()
                .where(PatientBeanDao.Properties.Idcard.like("%" + bean.getIdcard() + "%"))
                .list();
        if (patientBeanList != null && patientBeanList.size() > 0) {
            //身份证号码已存在
            mvpView.addPatientBeanResult(AddPatientActivity.AddState.EXIST);
        } else {
            long state = patientDao.insert(bean);
            if (state == 0) {
                mvpView.addPatientBeanResult(AddPatientActivity.AddState.FAILURE);
            } else {
                mvpView.addPatientBeanResult(AddPatientActivity.AddState.SUCCESS);
            }
        }
    }

    @Override
    public List<PatientBean> queryPatient(String content) {
        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(mvpView);
        WhereCondition like1 = PatientBeanDao.Properties.Idcard.like("%" + content + "%");
        WhereCondition like2 = PatientBeanDao.Properties.Name.like("%" + content + "%");
        List<PatientBean> list = patientDao.queryBuilder()
                .orderDesc(PatientBeanDao.Properties.AddDate)
                .whereOr(like1, like2)
                .list();
        return list;
    }

    @Override
    public List<PatientBean> queryIdCard(String idcard) {
        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(mvpView);
        List<PatientBean> patientBeanList = patientDao.queryBuilder()
                .where(PatientBeanDao.Properties.Idcard.eq(idcard))
                .list();
        if (patientBeanList != null && patientBeanList.size() > 0) {
            //身份证号码已存在
            return patientBeanList;
        }
        return new ArrayList<>();
    }

    @Override
    public List<PatientBean> queryAllPatient() {
        // TODO 实现分页加载
        PatientBeanDao patientDao = GreenDaoManager.getPatientDao(mvpView);
        return patientDao.queryBuilder().orderDesc(PatientBeanDao.Properties.AddDate).list();
    }
}
